package com.cn.dream_order_server.util;

import java.util.Map;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class CacheObject implements Delayed {

    private Map<String,Object> data;
    /**
     * 缓存存在的时间，以秒为单位
     */
    private Long timeDelay;
    /**
     * 是否为永不失效缓存
     */
    private Boolean isPermanent;
    /**
     * 创建对象时的时间戳
     */
    private Long currentTimeStampt;


    private CacheObject(Map<String, Object> data, Long timeDelay, Boolean isPermanent) {
        super();
        this.setData(data);
        this.timeDelay = timeDelay;
        this.isPermanent = isPermanent;
        this.currentTimeStampt = System.currentTimeMillis();
    }
    public static CacheObject buildPermanentObject(Map<String,Object> data) {
        return new CacheObject(data, 0l, true);
    }
    public static CacheObject buildTemporaryObject(Map<String,Object> data, Long delayTime) {
        return new CacheObject(data, delayTime, false);
    }
    @Override
    public int compareTo(Delayed o) {
        CacheObject delay = (CacheObject)o;
        //永不过期
        if(isPermanent) {
            return 1;
        }else if(delay.isPermanent) {
            return -1;
        }
        return this.getDelay(TimeUnit.NANOSECONDS) - delay.getDelay(TimeUnit.NANOSECONDS) > 0 ? 1:-1;
    }

    /**返回的值小于或等于0时发生到期
     *
     */
    @Override
    public long getDelay(TimeUnit unit) {
        //永不过期
        if(isPermanent)
            return 1 * 1000;
        return currentTimeStampt + timeDelay * 1000 - System.currentTimeMillis();
    }
    public Map<String,Object> getData() {
        return data;
    }
    public void setData(Map<String,Object> data) {
        this.data = data;
    }
    @Override
    public String toString() {
        return "CacheObject [data = "+data.toString()+"],过期时间为[delayTime = "+timeDelay+"秒]";
    }

}
